package com.sensePlusVR.bean;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.xutils.DbManager;
import org.xutils.db.annotation.Column;
import org.xutils.db.annotation.Table;

import android.content.Context;

import com.sensePlusVR.application.VRApplication;
import com.sensePlusVR.base.EntityBase;
import com.sensePlusVR.manager.DataCenter;
import com.sensePlusVR.utils.FileUtils;
import com.sensePlusVR.utils.GameDownload;
import com.sensePlusVR.utils.MyLog;

@Table(name = "ColletionItem")
public class CollectionItem extends EntityBase{
	
	private static final String TAG = CollectionItem.class.getSimpleName();
	
	public static final int DownloadNone = 0;//仅仅搜藏
	
	public static final int DownloadError = 1;//下载失败
	
	public static final int DownloadPause = 2;//下载暂停
	
	public static final int DownloadDoing = 3;//下载进行中
	
	public static final int DownloadFinished = 4;//下载完成
	
	public static final int DownloadPending = 5;//网络问题处于pending状态
	//public static final int DownloadUpgrade = 5;//需要更新的临时状态
	
	
	@Column(name = "gameId")
	private int gameId;//游戏id
	
	@Column(name = "downloadState")
	private int downloadState;//下载状态 ：0未下载 1下载失败  2下载暂停   3正在下载 4下载完成
	
	@Column(name = "totalLen")
	private long totalLen;
	
	@Column(name = "downProgress")
	private int downProgress;//下载进度 只有在暂停状态下保存
	
	
	@Column(name = "downloadTime")
	private long downloadTime;//开始下载时间
	
	@Column(name = "topSort")
	private long topSort;//置顶标记参数

	

	@Override
	public String toString() {
		return "CollectionItem [gameId=" + gameId + ", downloadState="
				+ downloadState + ", totalLen=" + totalLen + ", downProgress="
				+ downProgress + ", downloadTime=" + downloadTime
				+ ", topSort=" + topSort + "]";
	}

	public int getGameId() {
		return gameId;
	}

	public void setGameId(int gameId) {
		this.gameId = gameId;
	}

	public int getDownloadState() {
		return downloadState;
	}

	public void setDownloadState(int downloadState) {
		this.downloadState = downloadState;
	}

	public long getTotalLen() {
		return totalLen;
	}

	public void setTotalLen(long totalLen) {
		this.totalLen = totalLen;
	}

	public int getDownProgress() {
		return downProgress;
	}

	public void setDownProgress(int downProgress) {
		this.downProgress = downProgress;
	}

	public long getDownloadTime() {
		return downloadTime;
	}

	public void setDownloadTime(long downloadTime) {
		this.downloadTime = downloadTime;
	}
	
	public long getTopSort() {
		return topSort;
	}

	public void setTopSort(long topSort) {
		this.topSort = topSort;
	}


	
	
	/**
	 * 保存或者更新
	 * @param collectionItem
	 */
	public static void saveOrUpdate(final CollectionItem collectionItem) {
		try {
			Context context = VRApplication.getAppContext();
			if (context != null) {
				DbManager db = VRApplication.getDbManager();
				db.saveOrUpdate(collectionItem);
			}
		} catch (Exception e) {
			MyLog.e(TAG, "ColletionItem saveOrupdate failed: " + e);
		}
	}
	
	/**
	 * 删除
	 * @param collectionItem
	 */
	public static void delete(final CollectionItem collectionItem) {
		new Thread(){
			public void run() {
				try {
					Context context = VRApplication.getAppContext();
					if (context != null) {
						DbManager db = VRApplication.getDbManager();
						db.delete(collectionItem);
					}
				} catch (Exception e) {
					MyLog.e(TAG, "ColletionItem delete failed: " + e);
				}
		
			};
		}.start();
	}
	
	
	/**
	 * 根据gameId查询 注：查询成功表示已经收藏
	 * @param gameId
	 * @return
	 */
	public static CollectionItem query(int gameId){
		//过滤非真人
		GameItem gItem = GameItem.getGameById(gameId);
		if(gItem != null && !GameItem.isRealGame(gItem)){
			return null;
		}
		try {
    		Context context = VRApplication.getAppContext();
    		if(context != null) {
    			DbManager db = VRApplication.getDbManager();
	    		return db.selector(CollectionItem.class).where("gameId","=",gameId).findFirst();
    		}
    	}catch(Exception e){
    		MyLog.e(TAG, "query:"+gameId+" failed: "+e);
    	}
    	return null;
	}
	
	/**
	 * 是否正在下载或者下载完成
	 * @param collection
	 */
	public static boolean isDownloadingOred(CollectionItem collection){
		
		return collection.getDownloadState()>DownloadNone;
	}
	
	/**
	 * 获取所有的搜藏选项
	 * @return
	 */
	public static List<CollectionItem> getAllCollectionItems(){
		try {
    		Context context = VRApplication.getAppContext();
    		if(context != null) {
    			DbManager db = VRApplication.getDbManager();
    			List<CollectionItem> collectionAll = db.selector(CollectionItem.class).orderBy("topSort", true).findAll();
    			if(collectionAll != null){
    				collectionAll = getRealItems(collectionAll);
    			}
	    		return collectionAll;
    		}
    	}catch(Exception e){
    		MyLog.e(TAG, "getAllCollectionItems failed: "+e);
    	}
    	return null;
	}
	
	
	/**
	 * 获取所有已经下载的搜藏项
	 * @return
	 */
	public static List<CollectionItem> getAllDownloadedCollectionItems(){
		
		try {
    		Context context = VRApplication.getAppContext();
    		if(context != null) {
    			DbManager db = VRApplication.getDbManager();
    			List<CollectionItem> collectionAll = db.selector(CollectionItem.class).where("downloadState", "=",DownloadFinished).orderBy("downloadTime", true).findAll();
    			if(collectionAll != null){
    				collectionAll = getRealItems(collectionAll);
    			}
	    		return collectionAll;
    		}
    	}catch(Exception e){
    		MyLog.e(TAG, "getAllDownloadedCollectionItems failed: "+e);
    	}
    	return null;
	}
	
	
	/**
	 * 获取所有没有下载完成的选项
	 * @return
	 */
	public static List<CollectionItem> getAllNotDownloadedCollectionItems(){
		try {
    		Context context = VRApplication.getAppContext();
    		if(context != null) {
    			DbManager db = VRApplication.getDbManager();
    			List<CollectionItem> collectionAll = db.selector(CollectionItem.class).where("downloadState", "!=",DownloadFinished).orderBy("downloadTime", true).findAll();
    			if(collectionAll != null){
    				collectionAll = getRealItems(collectionAll);
    			}
	    		return collectionAll;
    		}
    	}catch(Exception e){
    		MyLog.e(TAG, "getAllNotDownloadedCollectionItems failed: "+e);
    	}
    	return null;
	}
	
	private static List<CollectionItem> getRealItems(List<CollectionItem> oldCollcetionList){
		List<CollectionItem> newCollcetionList = new ArrayList<CollectionItem>();
		for(CollectionItem clcItem : oldCollcetionList){
			GameItem gItem = GameItem.getGameById(clcItem.getGameId());
			if(gItem != null && GameItem.isRealGame(gItem)){
				newCollcetionList.add(clcItem);
			}
		}
		return newCollcetionList;
		
	}
	
	/**
	 * 是否需要下载
	 * @param CollectionItem
	 * @return
	 */
	public static boolean needToDownload(CollectionItem clcItem){
		
		
		if(clcItem==null){
			
			return true;
		}
		
		int state = clcItem.getDownloadState();
		
		if(state==CollectionItem.DownloadNone||state==CollectionItem.DownloadError||state==CollectionItem.DownloadPause){
			
			return true;
		}
		
		return false;
	}
	
	
	/**
	 * 是否需要下载
	 * @param gameItem
	 * @return
	 */
	public static boolean needToDownload(GameItem gameItem){
		
		CollectionItem clcItem = CollectionItem.query(gameItem.getId());
		
		return needToDownload(clcItem);
	}
	
	
//	/**
//	 * 是否为仅仅收藏
//	 * @param gameItem
//	 * @return
//	 */
//	public static boolean isDownloadUpgrade(GameItem gameItem) {
//
//		CollectionItem clcItem = CollectionItem.query(gameItem.getId());
//
//		if (clcItem == null)
//			return false;
//
//		int state = clcItem.getDownloadState();
//		if (state == CollectionItem.DownloadUpgrade)
//			return true;
//		return false;
//	}
	
	/**
	 * 是否为仅仅收藏
	 * @param gameItem
	 * @return
	 */
	public static boolean isDownloadNone(GameItem gameItem) {

		CollectionItem clcItem = CollectionItem.query(gameItem.getId());

		if (clcItem == null)
			return false;

		int state = clcItem.getDownloadState();
		if (state == CollectionItem.DownloadNone)
			return true;
		return false;
	}
	
	/**
	 * 是否为正在下载
	 * @param gameItem
	 * @return
	 */
	public static boolean isDownloading(GameItem gameItem) {

		CollectionItem clcItem = CollectionItem.query(gameItem.getId());

		if (clcItem == null)
			return false;

		int state = clcItem.getDownloadState();
		if (state == CollectionItem.DownloadDoing)
			return true;
		return false;
	}
	
	/**
	 * 是否为正在下载
	 * @param gameItem
	 * @return
	 */
	public static boolean isDownloadError(GameItem gameItem) {

		CollectionItem clcItem = CollectionItem.query(gameItem.getId());

		if (clcItem == null)
			return false;

		int state = clcItem.getDownloadState();
		if (state == CollectionItem.DownloadError)
			return true;
		return false;
	}
	
	/**
	 * 是否为已经下载
	 * @param gameItem
	 * @return
	 */
	public static boolean isDownloaded(GameItem gameItem) {

		CollectionItem clcItem = CollectionItem.query(gameItem.getId());

		if (clcItem == null)
			return false;

		int state = clcItem.getDownloadState();
		if (state == CollectionItem.DownloadFinished)
			return true;
		return false;
	}
	
	/**
	 * 是否为正在下载
	 * @param gameItem
	 * @return
	 */
	public static boolean isDownloadPause(GameItem gameItem) {

		CollectionItem clcItem = CollectionItem.query(gameItem.getId());

		if (clcItem == null)
			return false;

		int state = clcItem.getDownloadState();
		if (state == CollectionItem.DownloadPause)
			return true;
		return false;
	}
	
	

	/**
	 * 增加搜藏
	 * @param gameItem
	 */
	public static void addCollection(GameItem gameItem){
		
		CollectionItem clcItem = CollectionItem.query(gameItem.getId());
		
		if(clcItem!=null){
	
			return;
		}
		
		clcItem = new CollectionItem();
		
		clcItem.setGameId(gameItem.getId());
		
		clcItem.setDownloadState(CollectionItem.DownloadNone);
		
		CollectionItem.saveOrUpdate(clcItem);
		
		//增加共有资源
		List<String> urls = GameDownload.GameUrls(gameItem);
		String savePath = GameDownload.getRootPath(gameItem);
		for(String url:urls){
			
			String fileName = FileUtils.getFileName(url);
			String filePath = savePath + File.separator + fileName;
			
			GameUrl gameUrl = GameUrl.query(url);
			
			if(gameUrl!=null){
				
				gameUrl.setDownloadCount(gameUrl.getDownloadCount()+1);
				
			}else{
				
				gameUrl = new GameUrl();
				
				gameUrl.setUrl(url);
				
				gameUrl.setSavePath(filePath);
				
				gameUrl.setFileName(fileName);
				
				gameUrl.setDownloadCount(1);
				
			}
			
			GameUrl.saveOrUpdate(gameUrl);
		}
		
		DataCenter.getInstans().CollectionGameAdd(gameItem.getId());
	}
	
	/**
	 * 添加到CollcetionItem列表
	 * @param gameItem
	 */
	public static void addCollectionItem(GameItem gameItem){
		
		CollectionItem clcItem = CollectionItem.query(gameItem.getId());
		
		if(clcItem!=null){
	
			return;
		}
		
		clcItem = new CollectionItem();
		
		clcItem.setGameId(gameItem.getId());
		
		clcItem.setDownloadState(CollectionItem.DownloadNone);
		
		CollectionItem.saveOrUpdate(clcItem);
		
		//增加共有资源
		List<String> urls = GameDownload.GameUrls(gameItem);
		String savePath = GameDownload.getRootPath(gameItem);
		for(String url:urls){
			
			String fileName = FileUtils.getFileName(url);
			String filePath = savePath + File.separator + fileName;
			
			GameUrl gameUrl = GameUrl.query(url);
			
			if(gameUrl!=null){
				
				gameUrl.setDownloadCount(gameUrl.getDownloadCount()+1);
				
			}else{
				
				gameUrl = new GameUrl();
				
				gameUrl.setUrl(url);
				
				gameUrl.setSavePath(filePath);
				
				gameUrl.setFileName(fileName);
				
				gameUrl.setDownloadCount(1);
				
			}
			
			GameUrl.saveOrUpdate(gameUrl);
		}
	}
	
	/**
	 * 取消搜藏
	 * @param gameItem
	 */
	public static void cancelCollection(final GameItem gameItem,boolean isDelDownloadRes){
		DataCenter.getInstans().CollectionGameDel(gameItem.getId());
		CollectionItem clcItem = CollectionItem.query(gameItem.getId());
		//数据库中取消
		CollectionItem.delete(clcItem);
				
		GameDownload.rmRunningProgress(gameItem.getId());
		
		//如果不清除游戏资源则return
		if(!isDelDownloadRes)return;
		
		if(clcItem==null){
	
			return;
		}
		
		BuriePointEventReqDto buriePointEventReqDto = BuriePointEventReqDto.getBuriePointByClcItemId(clcItem.get_id());
		if(buriePointEventReqDto != null){
			
			if(clcItem.getDownloadState() != CollectionItem.DownloadFinished){
				
				BuriePointEventReqDto.delItem(buriePointEventReqDto);
				
			}
			
			
		}
		
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				//清除本地游戏资源
				List<String> urls = GameDownload.GameUrls(gameItem);
				
				//遍历url
				for(String url:urls){
					
					MyLog.d(TAG, "url : " + url);
					
					GameUrl gameUrl = GameUrl.query(url);
					
					if(gameUrl!=null){
						
						MyLog.d(TAG, "gameUrl : " + gameUrl.toString());
						
						int count = gameUrl.getDownloadCount() - 1;
						
						//删除资源和数据
						if(count==0){
							
							//删除资源
							boolean isDelUrl = FileUtils.deleteFile(gameUrl.getSavePath());
							boolean isDelUrlTmp = FileUtils.deleteFile(gameUrl.getSavePath()+".tmp");
							
							MyLog.d(TAG, "isDelUrl : " + isDelUrl + " isDelUrlTmp : " + isDelUrlTmp);
							
							//更新数据库
							GameUrl.delete(gameUrl);
							
						}else{//仅仅更新数据
							
							gameUrl.setDownloadCount(count);
							
							GameUrl.saveOrUpdate(gameUrl);
						}
								
					}		
					
				}
			}
		}).start();
	}
	
	
	

	
	
	
	
	
	
	
	

}
